package com.ssyc.gsk_tk.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyListView;
import com.ssyc.gsk_tk.R;
import com.ssyc.gsk_tk.bean.OverQuestion;
import com.ssyc.gsk_tk.bean.QuestionInfo;
import com.ssyc.gsk_tk.bean.SentenceInfo;
import com.ssyc.gsk_tk.util.TkKeys;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 句子改错
 * Created by Administrator on 2018/9/3 0003.
 */

public class TkSentenceChangeErrorFragment extends LazyBaseFragment implements View.OnClickListener {

    //未完成页面对象
    private QuestionInfo.ListBean.ItemBean info;
    //页面的json数据
    private String jsonData;

    //已完成的页面对象
    private OverQuestion.ListBean.ItemBean overinfo;

    //以完成状态下的解析
    private String explain;

    //页面数据模型
    private SentenceInfo sentenceInfo;

    //需要显示的题目内容
    private String questionContent;

    //正确答案
    private String rightAnswer;

    //题目
    private TextView tv_content;

    //用于保存需要变色的单词集合
    private List<String> wordMap = new ArrayList<>();

    //展示用户选择的单词
    private TextView tv_choose_word;

    //展示用户输入的单词
    private TextView tv_input_word;

    //顶部的你的作答有两种情况需要展示,一种是未完成状态下你填写答案后需要显示,另外一种是已完成状态下进入就需要展示
    private LinearLayout ll_your_answer;

    //展示你的作答,正确答案,每个选项的正确率以及题目解析的相关视图
    //该视图只有在已完成状态下才显示出来
    private LinearLayout llShowAnswer;
    //你的答案
    private TextView tv_own_answer;
    //正确答案
    private TextView tv_right_answer;
    //展示选项正确率的ListView
    private MyListView lv_show_answer;
    //正确率
    private TextView tv_persent;
    //解析
    private TextView tv_parse_answer;

    //记录点击选择文字的位置的值
    private int chooseTvPos = -1;

    public static final TkSentenceChangeErrorFragment newInstance(QuestionInfo.ListBean.ItemBean item, OverQuestion.ListBean.ItemBean overData) {
        TkSentenceChangeErrorFragment teacherGoldFragment = new TkSentenceChangeErrorFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", item);
        bundle.putSerializable("overdata", overData);
        teacherGoldFragment.setArguments(bundle);
        return teacherGoldFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tk_sentence_change_error;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void init(View view, Bundle savedInstanceState) {
        super.init(view, savedInstanceState);
        //显示内容
        showContent();

        //初始化视图
        initView(view);

        //获取页面对象
        initIntent();
    }

    /**
     * 获取页面对象
     */
    private void initIntent() {
        info = (QuestionInfo.ListBean.ItemBean) getArguments().getSerializable("data");

        //已完成的数据对象
        overinfo = (OverQuestion.ListBean.ItemBean) getArguments().getSerializable("overdata");

        //根绝是否是已完成和未完成的状态来设置答案展示部分是否需要显示以及点击TextView是否需要弹框操作
        if (overinfo != null) {
            //已完成状态不需要点击事件
            tv_input_word.setEnabled(false);
            llShowAnswer.setVisibility(View.VISIBLE);
        } else if (info != null) {
            ll_your_answer.setVisibility(View.GONE);
            llShowAnswer.setVisibility(View.GONE);
            tv_input_word.setEnabled(true);
            tv_input_word.setOnClickListener(this);
        }

        if (null != info) {
            //获取页面的JSON数据
            jsonData = info.getContent();
            if (!TextUtils.isEmpty(jsonData)) {
                sentenceInfo = GsonUtil.jsonToBean(jsonData, SentenceInfo.class);
                if (null != sentenceInfo) {
                    questionContent = sentenceInfo.getContent();
                    rightAnswer = sentenceInfo.getRight();

                    //设置未完成问题内容并且做单词的颜色标记化处理
                    initQuestionMethod(true);
                }
            }

        } else if (null != overinfo) {
            //如果是已完成则解析overinfo
            jsonData = overinfo.getContent();
            if (!TextUtils.isEmpty(jsonData)) {
                sentenceInfo = GsonUtil.jsonToBean(jsonData, SentenceInfo.class);
                //获取解析,注意:这里的解析只有一个
                explain = overinfo.getAnalysis();

                //设置已完成的数据展示
                initHasCompetedData();
            }
        }
    }


    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        tv_content = view.findViewById(R.id.tv_content);
        llShowAnswer = view.findViewById(R.id.ll_show_answer);
        tv_own_answer = view.findViewById(R.id.tv_own_answer);
        tv_right_answer = view.findViewById(R.id.tv_right_answer);
        lv_show_answer = view.findViewById(R.id.lv_show_answer);
        tv_parse_answer = view.findViewById(R.id.tv_parse_answer);
        tv_choose_word = view.findViewById(R.id.tv_choose_word);
        tv_input_word = view.findViewById(R.id.tv_input_word);
        tv_persent = view.findViewById(R.id.tv_persent);
        ll_your_answer = view.findViewById(R.id.ll_your_answer);
    }

    /**
     * 优化后的处理标题变色的方法
     *
     * @param flag 是否需要设置点击事件的方法,已完成状态下不需要设置点击事件
     */
    private void initQuestionMethod(boolean flag) {
        //获取需要显示的内容文本
        String questionContent = sentenceInfo.getContent();

        Log.i("test", "配置：" + questionContent);

        //使用￠进行切割,获取展示的问题和需要变色的单词
        String[] split = questionContent.split("￠");
        //获取文本
        String question = split[0];

        //获取需要变色的所有单词
        String[] words = split[1].split("#");

        //三个变色的span
        ForegroundColorSpan oneColorSpan = new ForegroundColorSpan(Color.parseColor("#1340e9"));
        ForegroundColorSpan twoColorSpan = new ForegroundColorSpan(Color.parseColor("#d934ff"));
        ForegroundColorSpan threeColorSpan = new ForegroundColorSpan(Color.parseColor("#15b624"));
        SpannableStringBuilder content = new SpannableStringBuilder(question);

        //将需要变色的三个变色的方法抽取
        List<ForegroundColorSpan> colorSpans = new ArrayList<>();
        colorSpans.add(oneColorSpan);
        colorSpans.add(twoColorSpan);
        colorSpans.add(threeColorSpan);

        for (int i = 0; i < words.length; i++) {
            int startIndex = startIndex(words[i], question);
            int end = startIndex + words[i].length();


            try {
                //变色处理
                content.setSpan(oneColorSpan, startIndex, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);



            if (flag) {
                //点击事件
                if (i == 0) {
                    content.setSpan(new TextOneClick() {
                        @Override
                        public void onClick(View widget) {
                            //点击事件
                            if (info != null) {
                                sysChooseTv(words[0]);
                                //记录选中文字的位置
                                chooseTvPos = 0;
                            }
                        }
                    }, startIndex, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else if (i == 1) {
                    content.setSpan(new TextTwoClick() {
                        @Override
                        public void onClick(View widget) {
                            //点击事件
                            if (info != null) {
                                sysChooseTv(words[1]);
                                //记录选中文字的位置
                                chooseTvPos = 1;
                            }
                        }
                    }, startIndex, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else if (i == 2) {
                    content.setSpan(new TextThreeClick() {
                        @Override
                        public void onClick(View widget) {
                            //点击事件
                            if (info != null) {
                                sysChooseTv(words[2]);
                                //记录选中文字的位置
                                chooseTvPos = 2;
                            }
                        }
                    }, startIndex, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            } catch (Exception e) {

            }
        }
        //设置问题需要显示的内容
        tv_content.setText(content);
        if (flag) {
            //设置该方法后,点击事件才能生效
            tv_content.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    /**
     * 获取指定单词在字符串中的位置
     *
     * @return
     */
    private int startIndex(String word, String question) {
        int startIndex = -1;
        //使用正则将问题中的所有"进行空格替换,并且加上前后空格
        String reg = "/[\",.!，。！“”]/g";
        String cloneQuestion = " " + question.replaceAll(reg, " ") + " ";

        //给需要查找的单词也加上前后空格
        String searchWord = " " + word + " ";
        if (cloneQuestion.startsWith(searchWord)) {
            startIndex = 0;
        } else {
            startIndex = cloneQuestion.indexOf(searchWord);
        }

        //防止找不到返回-1导致程序崩溃
        if (startIndex == -1) {
            startIndex = question.indexOf(word);
        }
        return startIndex;
    }


    /**
     * 点击变色文字后同步下部左边的TextView的方法
     *
     * @param word
     */
    private void sysChooseTv(String word) {
        if (!TextUtils.isEmpty(word)) {
            tv_choose_word.setText(word);
            //改变背景
            tv_choose_word.setBackgroundResource(R.drawable.tk_tv_sentece_choose_bg);
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_input_word) {
            //弹框输入英文单词
            showInputPop();
        }
    }

    /**
     * 弹出输入单词的PopUpWindow
     */
    private void showInputPop() {
        String chooseWord = tv_choose_word.getText().toString().trim();
        if (TextUtils.isEmpty(chooseWord)) {
            UiUtils.Toast("请先选择需要修改的单词", false);
            return;
        } else {
            PopUpManager.showPop(getContext(), R.layout.tk_pop_input_form_blank, 0.3f, getActivity(), new PopUpManager.onGetViewListener() {
                @Override
                public void getChildView(View view, int layoutResId) {
                    EditText et_input = view.findViewById(R.id.et_input);
                    TextView tv_cancel = view.findViewById(R.id.tv_cancel);
                    TextView tv_ok = view.findViewById(R.id.tv_ok);
                    TextView tvMsg = view.findViewById(R.id.tv_pop_content);
                    tvMsg.setText("正在修改单词 " + chooseWord);

                    tv_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            PopUpManager.dismiss();
                        }
                    });

                    tv_ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String inputWord = et_input.getText().toString().trim();
                            if (TextUtils.isEmpty(inputWord)) {
                                UiUtils.Toast("您还未输入单词", false);
                                return;
                            } else {
                                PopUpManager.dismiss();
                                //将输入的单词回显到TextView上
                                tv_input_word.setText(inputWord);

                                if (chooseTvPos == 0) {
                                    tv_input_word.setTextColor(getResources().getColor(R.color.tk_one_tv_selected));

                                } else if (chooseTvPos == 1) {
                                    tv_input_word.setTextColor(getResources().getColor(R.color.tk_two_tv_selected));

                                } else if (chooseTvPos == 2) {
                                    tv_input_word.setTextColor(getResources().getColor(R.color.tk_three_tv_selected));

                                }
                                //显示布局顶部的你的作答
                                ll_your_answer.setVisibility(View.VISIBLE);

                                //显示你的作答的内容
                                //获取题目的内容
                                String questionString = sentenceInfo.getContent().split("￠")[0];

                                //将题干中选择的单词替换成输入的单词并且进行对应的变色处理
                                //获取选择的单词在题干中的开始位置
                                int replaceStartIndex = startIndex(chooseWord, questionString);
                                //获取选择的单词在题干中的结束位置
                                int replaceEndIndex = replaceStartIndex + chooseWord.length();
                                //将题干中选择的单词替换成用户输入的单词,由于字符串的replace()方法不能指定位置进行替换,所以使用StringBuild来实现
                                StringBuilder stringBuilder = new StringBuilder(questionString);
                                stringBuilder.replace(replaceStartIndex, replaceEndIndex, inputWord);

                                //变色处理
                                SpannableStringBuilder sb = new SpannableStringBuilder(stringBuilder.toString());
                                int startColor = replaceStartIndex;
                                int endColor = startColor + inputWord.length();
                                //根据选择修改的单词修改不同颜色
                                if (chooseTvPos == 0) {
                                    sb.setSpan(new ForegroundColorSpan(Color.parseColor("#1340e9")), startColor, endColor, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                } else if (chooseTvPos == 1) {
                                    sb.setSpan(new ForegroundColorSpan(Color.parseColor("#d934ff")), startColor, endColor, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                } else if (chooseTvPos == 2) {
                                    sb.setSpan(new ForegroundColorSpan(Color.parseColor("#15b624")), startColor, endColor, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                }
                                tv_own_answer.setText(sb);

                                //通过EventBs将用户作答本小题的相关信息传递给TkMainActivity保存
                                //currPos对应的每个大题的小题的位置,本提醒默认就一个小题
                                int choosePos = 0;

                                //用户输入的单词
                                String chooseAnswer = inputWord;

                                //获取服务器返回的题目原句子和正确的答案句子
                                String rightAnswer = sentenceInfo.getRight();

                                //判断输入的答案是否如正确
                                boolean chooseResult = false;
                                if (rightAnswer.equals(sb.toString())) {
                                    //用户作答正确
                                    chooseResult = true;
                                } else {
                                    //用户作答错误
                                    chooseResult = false;
                                }

                                //回传当前提醒的TypeId,当前题型对应的是8
                                int typeId = 8;
                                BusInfo busInfo = new BusInfo();
                                busInfo.tkMsg = TkKeys.TKMsg;
                                busInfo.tkChoosePos = choosePos;
                                busInfo.tkChooseAnswer = tv_choose_word.getText().toString().trim() + "€" + chooseAnswer;
                                busInfo.tkChooseResult = chooseResult;
                                busInfo.typeId = typeId;
                                EventBus.getDefault().post(busInfo);
                            }
                        }
                    });
                }
            });
        }
    }

    /**
     * 点击事件,分别对应3种需要变色的文字颜色处理和点击事件
     */
    private abstract class TextOneClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
            ds.setColor(Color.parseColor("#1340e9"));
        }
    }

    private abstract class TextTwoClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
            ds.setColor(Color.parseColor("#d934ff"));
        }
    }

    private abstract class TextThreeClick extends ClickableSpan {
        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
            ds.setColor(Color.parseColor("#15b624"));
        }
    }


    /*-------------------以完成状态------------------------------*/

    /**
     * 设置已完成状态下的数据
     */
    private void initHasCompetedData() {
        //题目的正确答案
        String rightString = sentenceInfo.getRight();
        String questionString = sentenceInfo.getContent().split("￠")[0];

        //设置问题
        initQuestionMethod(true);

        //获取选择的单词和你输出的答案拼接
        String[] answers = overinfo.getOption_content().split("€");

        if (answers.length == 2) {
            //获取已完成状态下选择的单词在所有需要变色单词中的位置
            getChooseWordPos(answers[0]);

            //设置选择的单词和修改的单词
            tv_choose_word.setText(answers[0]);

            tv_choose_word.setBackgroundResource(R.drawable.tk_tv_sentece_choose_bg);

            tv_input_word.setText(answers[1]);

            //根据选择修改的单词修改不同颜色
            if (chooseTvPos == 0) {
                tv_input_word.setTextColor(getResources().getColor(R.color.tk_one_tv_selected));
            } else if (chooseTvPos == 1) {
                tv_input_word.setTextColor(getResources().getColor(R.color.tk_two_tv_selected));
            } else if (chooseTvPos == 2) {
                tv_input_word.setTextColor(getResources().getColor(R.color.tk_three_tv_selected));
            }

            //设置你的作答和正确答案
            //你的作答
            //获取选择的单词在题干中的开始位置
            int replaceStartIndex = startIndex(answers[0], questionString);
            //获取选择的单词在题干中的结束位置
            int replaceEndIndex = replaceStartIndex + answers[0].length();
            //将题干中选择的单词替换成用户输入的单词,由于字符串的replace()方法不能指定位置进行替换,所以使用StringBuild来实现
            StringBuilder stringBuilder = new StringBuilder(questionString);
            stringBuilder.replace(replaceStartIndex, replaceEndIndex, answers[1]);

            //变色处理
            SpannableStringBuilder sb = new SpannableStringBuilder(stringBuilder.toString());
            int startColor = replaceStartIndex;
            int endColor = startColor + answers[1].length();
            //根据选择修改的单词修改不同颜色
            if (chooseTvPos == 0) {
                sb.setSpan(new ForegroundColorSpan(Color.parseColor("#1340e9")), startColor, endColor, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (chooseTvPos == 1) {
                sb.setSpan(new ForegroundColorSpan(Color.parseColor("#d934ff")), startColor, endColor, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (chooseTvPos == 2) {
                sb.setSpan(new ForegroundColorSpan(Color.parseColor("#15b624")), startColor, endColor, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            tv_own_answer.setText(sb);

            //正确答案
            tv_right_answer.setText(rightString);
        }

        //正确率
        if (overinfo != null) {
            if (overinfo.getProbability() != null && overinfo.getProbability().size() != 0) {
                tv_persent.setText(overinfo.getProbability().get(0).getpro());
            } else {
                tv_persent.setText("100.0%");
            }
        }

        //解析
        tv_parse_answer.setText(explain);
    }

    private void getChooseWordPos(String answer) {
        //获取选择的单词在正确答案中的位置
        //获取需要显示的内容文本
        String questionContent = sentenceInfo.getContent();

        //使用￠进行切割,获取展示的问题和需要变色的单词
        String[] split = questionContent.split("￠");

        //获取文本
        String question = split[0];

        //获取需要变色的所有单词
        String[] words = split[1].split("#");

        //确定选择的单词在所有单词中的位置
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(answer)) {
                chooseTvPos = i;
                break;
            }
        }
    }
}
